package per.hx.bs.aspect;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import per.hx.bs.base.annotation.BsCLog;
import per.hx.bs.base.entity.BsLogDO;
import per.hx.bs.service.LogService;
import per.hx.bs.shiro.ShiroUser;
import per.hx.bs.utils.BscLogUtils;

import java.lang.reflect.Method;

/**
 * @author HuXing
 * @date 2018/3/26  15:45
 */
@Component
public class SaveLogTask {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private final
    LogService logService;

    @Autowired
    public SaveLogTask(LogService logService) {
        this.logService = logService;
    }

    @Async
    public void saveLog(ProceedingJoinPoint joinPoint, long time, String ip) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        BsLogDO bsLogDO = new BsLogDO();
        BsCLog bsCLog = method.getAnnotation(BsCLog.class);

        // 注解上的描述
        if (bsCLog != null) {
            bsLogDO.setOperation(bsCLog.value());
        }

        // 请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        bsLogDO.setMethod(className + "." + methodName + "()");
        // 请求的参数
        Object[] args = joinPoint.getArgs();
        try {
            String params = JSON.toJSONString(args[0]);
            bsLogDO.setParams(params);
        } catch (Exception e) {
            bsLogDO.setParams(e.getMessage());
        }

        // 设置IP地址
        bsLogDO.setIp(ip);
        // 用户名
        ShiroUser shiroUser = BscLogUtils.getUser();

        if (shiroUser == null) {
            if (bsLogDO.getParams() != null) {
                bsLogDO.setUserId(-1L);
                bsLogDO.setUsername(bsLogDO.getParams());
            } else {
                bsLogDO.setUserId(-1L);
                bsLogDO.setUsername("获取用户信息为空");
            }
        } else {
            bsLogDO.setUserId(shiroUser.getUserId());
            bsLogDO.setUsername(shiroUser.getUserName());
        }
        bsLogDO.setTime((int) time);

        // 保存系统日志
        logger.info(bsLogDO.toString());
        logService.insert(bsLogDO);
    }
}
